package com.lastproject.web.bean;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;

import com.lastproject.dto.SubcategoryDTO;
import com.lastproject.ejb.dao.CheckPermissionDAORemote;
import com.lastproject.ejb.dao.SubcategoryDAORemote;

public class SubcategoryBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7803521146539604670L;

	@EJB
	SubcategoryDAORemote subcategoryDAORemote;

	SubcategoryDTO subcategoryDTO;

	private boolean alreadyCreated = false;

	public SubcategoryBean() {

	}

	@EJB
	CheckPermissionDAORemote checkPermissionDAORemote;
	
	public void preRenderView(ComponentSystemEvent event) {
        if (!checkPermissionDAORemote.hasSurveyManagementRights(true)){
        	FacesContext fc = FacesContext.getCurrentInstance();
        	ExternalContext ec = fc.getExternalContext();
        	try {
				ec.redirect("restrictedAccess.xhtml");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
    }
	/**
	 * Create a subcategory
	 * 
	 * @return Returns a String containing [nextPage].xhtml
	 */
	public String createSubcategory() {
		setAlreadyCreated(false);
		List<SubcategoryDTO> subcatList = new ArrayList<SubcategoryDTO>();
		subcatList = subcategoryDAORemote.findAll();

		for (SubcategoryDTO s : subcatList) {
			if (s.getName().equals(subcategoryDTO.getName())) {
				alreadyCreated = true;
			}
		}

		if (alreadyCreated == false) {
			subcategoryDAORemote.create(subcategoryDTO);

			subcategoryDTO.setName("");
			return "createTopic.xhtml";
		}

		return "createSubcategory.xhtml";
	}

	public String back() {
		subcategoryDTO.setName("");
		alreadyCreated = false;
		return "createTopic.xhtml";
	}

	public SubcategoryDTO getSubcategoryDTO() {
		return subcategoryDTO;
	}

	public void setSubcategoryDTO(SubcategoryDTO subcategoryDTO) {
		this.subcategoryDTO = subcategoryDTO;
	}

	public boolean isAlreadyCreated() {
		return alreadyCreated;
	}

	public void setAlreadyCreated(boolean alreadyCreated) {
		this.alreadyCreated = alreadyCreated;
	}

}
